import _ from 'love-u'

import config from './config'
import { $setCache, $getCache, } from './storage'

/**
 * 获取前一页的Page对象
 * @returns 
 */
export function $prevPage() {
	let pages = getCurrentPages()
	return pages[pages.length - 2]
}

/**
 * 获取当前路由路径
 */
export function $currentRoute() {
	let { route, options } = _.last(getCurrentPages())
	return $makeUrl(route, options) //拼接路径，把参数也带着
}

/**
 * 拼接URL,避免拼接字符串
 * @param {String} url
 * @param {Object} args
 */
export function $makeUrl(url, args) {
	if (!args) return url
	let params = _.convertObj2Str(args)
	if (!params) return url
	return [url, params].join('?')
}

/**
 * 跳转页面，内部自动处理了tabbar的跳转
 */
export function $go2(url, isRedirect = false) {
	//如果是tabbar里面的页面， 需要switchTab，所以需要第二个参数
	let isTab = config.TABBAR_PAGE_LIST.includes(url)
	uni[isTab ? 'switchTab' : isRedirect ? 'redirectTo' : 'navigateTo']({ url })
}

/**
 * 返回
 */
export const $back = () => {
	$prevPage() && uni.navigateBack() || $go2(config.HOME_PAGE_PATH, true)
}

/**
 * 拦截，重定向到登录页
 */
export function $redirect2Login(fromPath = '') {
	if (!fromPath) fromPath = '/' + $currentRoute()
	$setCache(config.KEY_REDIRECT_PATH, fromPath)
	
	if(fromPath === '/pages/account/phone-login') return 
	
	// #ifdef MP-WEIXIN
	$go2(config.WEIXIN_LOGIN_PAGE_PATH, true)
	// #endif
	// #ifndef MP-WEIXIN
	$go2(config.LOGIN_PAGE_PATH, true)
	// #endif
}

/**
 * 登录后跳转
 * 跳转回去或者到首页
 */
export function $redirectAfterLogin() {
	// 是否有被拦截的来源页面
	let redirect = $getCache(config.KEY_REDIRECT_PATH) || config.HOME_PAGE_PATH
	//如果之前就是登录页，那就去首页
	if ([config.LOGIN_PAGE_PATH, config.WEIXIN_LOGIN_PAGE_PATH].includes(redirect))
		redirect = config.HOME_PAGE_PATH
	//从登录跳转的话，需要redirect
	$go2(redirect, true)
}
